layui.define(['layer', 'form', 'aphp', 'table'], function (exports) {
    "use strict";

    var MOD_NAME = 'aphpForm',
        layer = layui.layer,
        $ = layui.$,
        form = layui.form,
        aphp = layui.aphp,
        table = layui.table;

    var init = {
        table_elem: '#currentTable',
        table_render_id: 'currentTable',
    };

    var aphpForm = {
        events: {
            // 下拉多选框组件
            xmSelect: function (layform) {
                if ($("[xm-select]", layform).length > 0) {
                    layui.define('select', function(exports) {
                        var select = layui.select;
                    });
                }
            },
            // 日期时间选择器
            datetimePicker: function (layform) {
                if ($(".datetime", layform).length > 0) {
                    layui.define('laydate', function (exports) {
                        var laydate = layui.laydate;
                        $(".datetime", layform).each(function () {
                            var format = $(this).attr('data-date'),
                                type = $(this).attr('data-date-type'),
                                range = $(this).attr('data-date-range');
                            if (type === undefined || type === '' || type === null) {
                                type = 'datetime';
                            }
                            var options = {
                                elem: this,
                                type: type,
                                trigger: 'click',
                            };
                            if (format !== undefined && format !== '' && format !== null) {
                                options['format'] = format;
                            }
                            if (range !== undefined) {
                                if (range === null || range === '') {
                                    range = '-';
                                }
                                options['range'] = range;
                                options['shortcuts'] = [
                                    {
                                        text: "今天",
                                        value: function () {
                                            var today = new Date();
                                            return [
                                                new Date(today.getFullYear(), today.getMonth(), today.getDate()),
                                                new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59)
                                            ];
                                        }
                                    },
                                    {
                                        text: "昨天",
                                        value: function () {
                                            var yesterday = new Date();
                                            yesterday.setDate(yesterday.getDate() - 1);
                                            return [
                                                new Date(yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate()),
                                                new Date(yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate(), 23, 59, 59)
                                            ];
                                        }
                                    },
                                    {
                                        text: "7天前",
                                        value: function () {
                                            var today = new Date();
                                            var sevenDaysAgo = new Date();
                                            sevenDaysAgo.setDate(today.getDate() - 7);
                                            return [
                                                new Date(sevenDaysAgo.getFullYear(), sevenDaysAgo.getMonth(), sevenDaysAgo.getDate()),
                                                new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59)
                                            ];
                                        }
                                    },
                                    {
                                        text: "本月",
                                        value: function () {
                                            var date = new Date();
                                            var year = date.getFullYear();
                                            var month = date.getMonth();
                                            return [
                                                new Date(year, month, 1),
                                                new Date(year, month + 1, 0, 23, 59, 59)
                                            ];
                                        }
                                    },
                                    {
                                        text: "上个月",
                                        value: function () {
                                            var date = new Date();
                                            var year = date.getFullYear();
                                            var month = date.getMonth();
                                            return [
                                                new Date(year, month - 1, 1),
                                                new Date(year, month, 0, 23, 59, 59)
                                            ];
                                        }
                                    }
                                ]
                            }
                            laydate.render(options);
                        });
                    })
                }
            },
            // 省市区选择组件
            cityPicker: function(layform) {
                // 绑定城市选择组件
                if ($("[data-toggle='city-picker']", layform).length > 0) {
                    layui.define('citypicker', function(exports) {
                        var citypicker = layui.citypicker;
                    });
                }
            },
            // 上传组件
            aphpUpload: function (layform) {
                if ($('.aphp-upload', layform).length > 0) {
                    layui.define('upload', function (exports) {
                        var upload = layui.upload;
                        $('.aphp-upload', layform).each(function () {
                            var field = $(this).data("field");
                            var upload_api = $(this).data("url") || GV.site + '/api/upload?api=image';
                            var accept = $(this).data("accept") || 'file'; //file image
                            var id = $(this).attr("id");
                            upload.render({
                                elem:'#' + id,
                                url: upload_api,
                                done:function(ret){
                                    if(ret.status === 1){
                                        $('#' + field).val(ret.data.path);
                                        if (accept === 'image') {
                                            $('#' + field + '-preview').attr('src', ret.data.path).show();
                                            $('#' + field + '-remove').show();
                                        }
                                    } else {
                                        layer.msg(ret.msg, { icon: 2, scrollbar: false, time: 3000, shadeClose: true });
                                    }
                                }
                            });
                            // 图片
                            if (accept === 'image') {
                                $('#' + field + '-remove').on('click',function(e){
                                    $('#' + field).val('');
                                    $('#' + field + '-preview').attr('src','').hide();
                                    $('#' + field + '-remove').hide();
                                    layui.stope(e);
                                });
                            }
                            $('#' + field + '-selected').on('click',function(){
                                var selected_api = $(this).data("url");
                                var width = 800;
                                var height = 600;
                                var area = [$(window).width() > width ? width + 'px' : '95%', $(window).height() > height ? height + 'px' : '95%'];
                                layer.open({
                                    title: "附件选择",
                                    type: 2,
                                    maxmin: true,
                                    shade: 0.1,
                                    area: area,
                                    content: selected_api,
                                    success: function (layero, index) {
                                        var body = layer.getChildFrame('body', index);
                                        body.find('#parent_field').html(field);
                                    }
                                });
                                return false;
                            });
                        });
                    });
                }
            },
            // 颜色选择组件
            colorPicker: function (layform) {
                if ($('.colorpicker', layform).length > 0) {
                    layui.define('colorpicker', function (exports) {
                        var colorpicker = layui.colorpicker;
                        $('.colorpicker', layform).each(function () {
                            var input_id = $(this).data("input-id");
                            var inputObj = $("#" + input_id);
                            colorpicker.render({
                                elem: $(this),
                                color: inputObj.val(),
                                done: function (color) {
                                    inputObj.val(color);
                                }
                            });
                        });
                    })
                }
            },
            // tinymce编辑器组件
            tinymce: function (layform) {
                var tinymces = {};
                if ($(".editor-tinymce", layform).length > 0) {

                    layui.define('tinymce', function (exports) {
                        var tinymce = layui.tinymce;

                        $('.editor-tinymce',layform).each(function() {
                            var editor_id = $(this).attr('id');
                            var editor_upload_url = $(this).attr('data-api') || GV.site + '/api/upload?api=image'; //GV.editor_upload_api
                            tinymces[editor_id] = tinymce.render({
                                elem: '#' + editor_id,
                                height: 400,
                                images_upload_handler: (blobInfo, success, failure) => {
                                    let formData = new FormData();
                                    formData.append('file', blobInfo.blob(), blobInfo.filename());
                                    $.ajax({
                                        url: editor_upload_url,
                                        data: formData,
                                        type: 'post',
                                        contentType: false,
                                        processData: false,
                                        success: function (res) {
                                            if (res.status === 1) {
                                                success(res.data.path)
                                            } else {
                                                failure(res.msg)
                                            }
                                        }
                                    });
                                }
                            });
                            tinymces[editor_id].on('change', function (e) {
                                var content = tinymces[editor_id].getContent();
                                $('#' + editor_id).val(content);
                            });
                        });
                    });
                }
            },
        },
        // 渲染表单
        bindEvent: function (form) {
            var events = aphpForm.events;
            form = typeof form === 'object' ? form : $(form);

            events.xmSelect(form); // 绑定下拉多选组件
            events.datetimePicker(form); // 绑定日期时间组件
            events.cityPicker(form); // 绑定省市区选择组件
            events.colorPicker(form); // 绑定颜色选择组件
            events.tinymce(form); // 绑定tinymce编辑器组件
            events.aphpUpload(form); // 绑定上传组件
        }
    };

    exports(MOD_NAME, aphpForm);
});